const { isRequired } = require("../utils");
const { Sequelize } = require("sequelize");

module.exports = (sequelize, DataTypes) => {
  const Menu = sequelize.define(
    "Menu",
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: Sequelize.UUIDV4,
        allowNull: false,
        primaryKey: true,
        comment: "菜单id",
      },
      parentId: {
        type: DataTypes.UUID,
        comment: "父级id",
        allowNull: true,
      },
      // 菜单与按钮进行分表设计，因此不需要menuType字段
      // menuType: {
      //   type: DataTypes.STRING,
      //   comment: "路由分类; 0:路由,1:按钮",
      //   allowNull: false,
      //   validate: {
      //     ...isRequired("分类"),
      //     isIn: {
      //       args: [[0, 1]],
      //       msg: "分类信息错误",
      //     },
      //   },
      // },
      path: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "路由地址",
        validate: isRequired("路由地址"),
      },
      title: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "路由名称",
        validate: isRequired("路由名称"),
      },
      routeName: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "路由标识",
        // 设置唯一不能重复
        unique: {
          msg: "routeName已存在",
        },
        validate: isRequired("routeName"),
      },
      icon: {
        type: DataTypes.STRING,
        comment: "menu图标",
      },
      component: {
        type: DataTypes.STRING,
        comment: "组件路径",
        allowNull: false,
        validate: isRequired("组件路径"),
      },
      // perms: {
      //   type: DataTypes.STRING,
      //   comment: "权限标识",
      // },
      sort: {
        type: DataTypes.INTEGER,
        comment: "排序",
        defaultValue: 0,
      },
    },
    {
      timestamps: true,
      tableName: "system_menu",
      createdAt: "createTime",
      updatedAt: "updateTime",
      comment: "路由表",
    }
  );
  Menu.associate = function (db) {
    // 菜单关联角色 多对多
    Menu.belongsToMany(db.Role, {
      through: db.RoleMenu,
      foreignKey: "menuId",
      as: "roles",
    });
    // 菜单关联按钮 一对多
    Menu.hasMany(db.MenuButton, {
      foreignKey: "parentId",
      sourceKey: "id",
      as: "buttons",
    });
  };
  return Menu;
};
